package cn.wolfcode.wolf2w.job;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyFavors;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVo;
import cn.wolfcode.wolf2w.redis.vo.TravelStatisVo;
import cn.wolfcode.wolf2w.service.IStrategyFavorsService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * 持久化定时任务，将redis中的vo、用户集合同步到数据库中
 */
@Component
public class RedisDataPersistenceJob {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private IStrategyFavorsService strategyFavorsService;

    @Autowired
    private ITravelService travelService;

    @Autowired
    private IUserInfoService userInfoService;

    // 定时任务处理（假设5秒一次持久化操作）
    @Scheduled(cron = "0/5 * * * * ? ")  // cron 定时规则（秒 分 时 几号 月 星期  Spring）  - 表示范围，从XX到XX触发一次； / 表示起始时间开始触发，然后每隔固定时间触发一次。
    public void doStrategyRedisWord(){
        System.out.println("---------- 攻略对象vo 持久化begin -----------");
          // 1、查询redis中所有的vo对象
        Set<String> keys = redisTemplate.keys(RedisKeys.STRATEGY_STATIS_VO.getPrefix() + "*");
        for (String key : keys) {
            // 2、将查询出来遍历，获取value并设置到数据库中
            String value = redisTemplate.opsForValue().get(key);
            StrategyStatisVo vo = JSON.parseObject(value, StrategyStatisVo.class);

            String strategyId = vo.getStrategyId();
            Strategy strategy = strategyService.get(strategyId);
            BeanUtils.copyProperties(vo,strategy);
            strategyService.update(strategy);
        }

        // 1、查询redis中所有的用户攻略收藏的list
        Set<String> favorListKeys = redisTemplate.keys(RedisKeys.USER_STRATEGY_FAVOR.getPrefix() + ":*");
        // 2、遍历，获取value并设置到数据库中
        for (String favorListKey : favorListKeys) {
            String value = redisTemplate.opsForValue().get(favorListKey);
            List<String> favors = JSON.parseArray(value, String.class);
            int index = favorListKey.indexOf(":");
            String usid = favorListKey.substring(index + 1);

            // 判断是否存在数据库，存在，更新；不存在，保存
            StrategyFavors sf = strategyFavorsService.queryByUsid(usid);
            if (sf == null){
                // 保存
                StrategyFavors strategyFavors = new StrategyFavors();
                strategyFavors.setUsid(usid);
                strategyFavors.setFavors(favors);
                strategyFavorsService.save(strategyFavors);
            }else {
                // 更新
                sf.setFavors(favors);
                strategyFavorsService.update(sf);
            }
        }
        System.out.println("---------- 攻略对象vo 持久化end -----------");
    }

    @Scheduled(cron = "0/5 * * * * ? ")
    public void doTravelRedisWord(){
        System.out.println("---------- 游记 持久化begin -----------");
        // vo
        Set<String> keys = redisTemplate.keys(RedisKeys.TRAVEL_STATIS_VO.getPrefix() + ":*");
        for (String key : keys) {
            String value = redisTemplate.opsForValue().get(key);
            TravelStatisVo vo = JSON.parseObject(value, TravelStatisVo.class);
            Travel travel = travelService.get(vo.getTravelId());
            BeanUtils.copyProperties(vo,travel);
            // 更新travel
            travelService.update(travel);
        }
        // list
        Set<String> listKeys = redisTemplate.keys(RedisKeys.USER_TRAVEL_FAVOR.getPrefix() + ":*");
        for (String listKey : listKeys) {
            String value = redisTemplate.opsForValue().get(listKey);
            List<String> list = JSON.parseArray(value, String.class);
            String[] split = listKey.split(":");
            UserInfo userInfo = userInfoService.get(split[1]);
            userInfo.setTravelFavors(list);
            userInfoService.update(userInfo);
        }
        System.out.println("---------- 游记 持久化end -----------");
    }
}
